//
//  YTKApi.m
//  YTKNetworkEncapsulation
//
//  Created by tianXin on 16/9/1.
//
//

#import "YTKApi.h"
#import "NSString+BYSAsistant.h"
#import "YTKNetworkConfig.h"
#import "MBProgressHUD.h"
#import "MBProgressHUD+assistant.h"
#import "HUB.h"
#import "HRTokenExpires.h"
@interface YTKApi ()
@property (nonatomic, strong)HRTokenExpires *tokenExpires;

@end
@implementation YTKApi




- (instancetype)init
{
    self = [super init];
    if (self) {
        _cacheTime = [[NSUserDefaults standardUserDefaults] integerForKey:@"cacheTime"];     //api缺省不缓存
        _tokenExpires = [HRTokenExpires new];

    }
    return self;
}

+ (YTKApi *)apiPostWithUrl:(NSString *)url para:(id)para{
    YTKApi *api = [[YTKApi alloc] init];
    api->_method = YTKRequestMethodPOST;
    api->_para = para;
    api->_url = url;
    api.requestSerializerType = YTKRequestSerializerTypeJSON;
    return api;
}

+ (YTKApi *)apiPutWithUrl:(NSString *)url para:(id)para
{
    YTKApi *api = [[YTKApi alloc] init];
    api->_method = YTKRequestMethodPUT;
    api->_para = para;
    api->_url = url;
    api.requestSerializerType = YTKRequestSerializerTypeJSON;
    return api;
}

+ (YTKApi *)apiPostWithUrl:(NSString *)url paraDictionary:(NSDictionary *)para{
    YTKApi *api = [[YTKApi alloc] init];
    api->_method = YTKRequestMethodPOST;
    api->_para = para;
    api->_url = url;
    api.requestSerializerType = YTKRequestSerializerTypeJSON;
    return api;
}

+ (YTKApi *)apiPostWithUrl:(NSString *)url parameter:(HRBaseRequstDataModel *)para{
    YTKApi *api = [[YTKApi alloc] init];
    api->_method = YTKRequestMethodPOST;
    api->_para = [para toDictionary];
    api->_url = url;
    api.requestSerializerType = YTKRequestSerializerTypeJSON;
    return api;
}


+ (YTKApi *)apiPutWithUrl:(NSString *)url parameter:(HRBaseRequstDataModel *)para
{
    YTKApi *api = [[YTKApi alloc] init];
    api->_method = YTKRequestMethodPUT;
    api->_para = [para toDictionary];
    api->_url = url;
    api.requestSerializerType = YTKRequestSerializerTypeJSON;
    return api;
}

+ (YTKApi *)apiGetWithUrl:(NSString *)url parameter:(HRBaseRequstDataModel *)para{
    YTKApi *api = [[YTKApi alloc] init];
    api->_method = YTKRequestMethodGET;
    api->_para = [para toDictionary];
    api->_url = url;
    api.requestSerializerType = YTKRequestSerializerTypeJSON;
    return api;
}

+ (YTKApi *)apiGetWithUrl:(NSString *)url para:(id)para{
    YTKApi *api = [[YTKApi alloc] init];
    api->_method = YTKRequestMethodGET;
    api->_para = para;
    api->_url = url;
    api.requestSerializerType = YTKRequestSerializerTypeJSON;
    return api;
}

+ (YTKApi *)apiDeleteWithUrl:(NSString *)url para:(id)para{
    YTKApi *api = [[YTKApi alloc] init];
    api->_method = YTKRequestMethodDELETE;
    api->_para = para;
    api->_url = url;
    api.requestSerializerType = YTKRequestSerializerTypeJSON;
    return api;
}

- (YTKApi *)appendUrlParameter:(NSNumber *)para{
    NSString *str = [NSString stringWithFormat:@"%ld",[para longValue]];
    _url = [_url stringByAppendingPathComponent:str];
    return self;
}

- (YTKApi *)appendUrlStringParameter:(NSString *)para{
    NSString *str = [NSString stringWithFormat:@"%@",para];
    _url = [_url stringByAppendingPathComponent:str];
    return self;
}

- (NSDictionary *)requestHeaderFieldValueDictionary {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

    if (self.foceNoTocken) {

        NSString *base64AuthCredentials = [[NSString stringWithFormat:@"%@:%@",TOKENAPPKEY,TOKENAPPSECRET] base64EncodedString];
        dict[@"Authorization"] = [NSString stringWithFormat:@"Basic %@", base64AuthCredentials];
    }else{
        NSString *utcTime = [NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]];
        dict[@"Authorization"] = [NSString stringWithFormat:@"Bearer %@",ACCESS_TOKEN];
        NSString *sha1 = [[NSString stringWithFormat:@"%@%@%@",TOKENAPPSECRET,utcTime,TOKENAPPKEY] sha1String];
        dict[@"AppKey"] = TOKENAPPKEY;
        dict[@"Utc-Time"] = utcTime;
        dict[@"Check-Sum"] = sha1;
        dict[@"currentUserLocalId"] = USERID;
        dict[@"platform"] = @"iOS";
        dict[@"uniqueIdentifier"] = [[NSUUID UUID] UUIDString];
    }
    return dict;

}

- (NSString *)requestUrl {
    return _url;
}

- (YTKRequestSerializerType)requestSerializerType {
    return _requestSerializerType;
}

- (YTKRequestMethod)requestMethod {
    return _method;
}

- (id)requestArgument {
    return _para;
}

- (void)printRequestInfo:(YTKBaseRequest *)request{
    DDLog(@"%@\n\n",self);
    NSString *logstr = nil;
    if (request.responseJSONObject) {
        NSDictionary *dict = request.responseJSONObject;
        logstr = [dict.description logString];
        DDLog(@"Api返回：\n%@\n\n",dict);

    }else{
        logstr = [request.responseString logString];
    }
    if ([logstr length]<20000) {
        DDLog(@"Api返回：\n%@\n\n",logstr);
    }
}

- (void)startWithCompletionBlockWithSuccess:(YTKRequestCompletionBlock)success
                                    failure:(YTKRequestCompletionBlock)failure{
    
    __block id safeSelf = self;
    if(![self.requestUrl isEqualToString:@"UserInfo/Put_UserCoordinate"] && ![self.requestUrl isEqualToString:@"System/Get_GetSounds"] && ![self.requestUrl isEqualToString:@"App/Get_GetSoundCardConfig"])
    {
        [self addAccessory:[HUB shareHub]]; //HUB插件
    }
    WeakSelf
    [self setSuccessCompletionBlock:^(__kindof YTKBaseRequest * _Nonnull request) {
        [safeSelf printRequestInfo:request];
        NSDictionary *dict = request.responseJSONObject;
        if ([dict[@"CodeStatus"] intValue] != 20000){
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showMessage:dict[@"Message"] finishBlock:nil];
            });
        }
        if([dict[@"CodeStatus"] intValue] != 20000 && ![self.requestUrl isEqualToString:@"UserInfo/Get_GetOtherLogin"] && ![self.requestUrl isEqualToString:@"App/Get_GetMatchUserInfo"] && ![self.requestUrl isEqualToString:@"UserInfo/Get_UserLogin"])
        {
            [[HUB shareHub] requestDidStop:@""];
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:WINDOW animated:YES];
            });
            return ;
        }
        
           success(request);
    }];
    
    [self setFailureCompletionBlock:^(__kindof YTKBaseRequest * _Nonnull request) {
        [safeSelf printRequestInfo:request];
        
        failure(request);

        
        if (request.responseStatusCode==0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showMessage:@"网络异常" finishBlock:nil];
            });
            return ;
        }else{
            NSString *errorString = [NSString stringWithFormat:@"请求失败, 状态码：%ld",(long)request.responseStatusCode];
            
            DDLog(@"%@url=========%@",errorString,weakSelf.requestUrl);

            dispatch_async(dispatch_get_main_queue(), ^{
                #if DEBUG
                [MBProgressHUD showMessage:errorString finishBlock:nil];

                #endif
                [MBProgressHUD hideHUDForView:WINDOW animated:YES];
            });
            return ;

        }
    }];
    [self start];
}

- (void)startWithSuccess:(void (^)(YTKBaseRequest *request))success{
    __block id safeSelf = self;
//    [self addAccessory:[HUB shareHub]]; //HUB插件
    [self setSuccessCompletionBlock:^(__kindof YTKBaseRequest * _Nonnull request) {
        [safeSelf printRequestInfo:request];
        success(request);
    }];
    [self setFailureCompletionBlock:^(__kindof YTKBaseRequest * _Nonnull request) {
        [safeSelf printRequestInfo:request];
        if (request.responseStatusCode==0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showMessage:@"网络异常" finishBlock:nil];
                [MBProgressHUD hideHUDForView:WINDOW animated:YES];
            });
            
        }else{
            NSString *errorString = [NSString stringWithFormat:@"请求失败, 状态码：%ld",(long)request.responseStatusCode];
            dispatch_async(dispatch_get_main_queue(), ^{
#if DEBUG
                [MBProgressHUD showMessage:errorString finishBlock:nil];
#endif
                [MBProgressHUD hideHUDForView:WINDOW animated:YES];
            });

        }

    }];
    [self start];
}

- (NSInteger)cacheTimeInSeconds{
    return _cacheTime;                     //缓存24小时
}

- (void)setCatchTime:(NSInteger)catchSeconds{
    _cacheTime = catchSeconds;
}


- (NSString *)description{
    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    NSString *apiName = self.apiName;
    if (!apiName) {
        apiName = @"";
    }
    NSString *str = [NSString stringWithFormat:@" \n\n------ 执行Api %@  \n\nbaseUrl = %@ \n\nurl = %@  \n\npara = %@ \n",apiName, config.baseUrl,_url,_para];
    return str;
}


- (void)getSuccessToken:(void(^)())isGetToken{
    [self.tokenExpires isTokenExpires:^(BOOL result) {
        [[HUB shareHub] requestDidStop:@""];

        if (result)
        {
            isGetToken(result);
            self.foceNoTocken = NO;
        }else{
        }
    }];
}
@end
